const {
    mysql,
    pool,
    router,
    Result,
    Myquery
} = require('../../connect');
const fs = require('fs')

// 获取所有的text数据
router.get('/textAll', (req, res) => {
    getText(req, res)
})
router.get('/getFile', (req, res) => {
    getFile(req, res)
})
router.get('/getData', (req, res) => {
    getData(req, res)
})

// 插入数据
function getText(req, res) {
    // 取传过来的text参数
    var id = req.params.id || req.query.id || req.body.id;
    console.log(req.params, req.query, req.body, '参数')
    var sql = 'SELECT * FROM node_one';
    if (id) {
        // 根据id查找数据
        sql = "select * from node_one where ?? = ?"
        var inserts = ['id', id]
        sql = mysql.format(sql, inserts)
    }
    new Myquery(sql, (err, r) => {
        let code = 200,
            data = r,
            msg = '成功';
        if (err) {
            code = 500;
            msg = "失败";
            data = null
        }
        res.json(new Result({
            msg,
            data,
            code
        }))
    })
}
function getData(req, res) {
    // 取传过来的text参数
    var id = req.params.id || req.query.id || req.body.id;
    console.log(req.params, req.query, req.body, '参数')
    var sql = 'SELECT * FROM node_one';
    if (id) {
        // 根据id查找数据
        sql = "select * from book where ?? = ?"
        var inserts = ['id', id]
        sql = mysql.format(sql, inserts)
    }
    new Myquery(sql, (err, r) => {
        let code = 200,
            data = r,
            msg = '成功';
        if (err) {
            code = 500;
            msg = "失败";
            data = null
        }
        res.json(new Result({
            msg,
            data,
            code
        }))
    })
}
// 插入数据
function getFile(req, res) {
    // 取传过来的text参数
    console.log(req)
    fs.readFile(req.query.path,(err,value)=>{
        if(err){
            res.json(new Result({
                data:err,
            }))
        }else{
            // res.setHeader('Access-Control-Allow-Origin','*')
            res.send(value)
        }
    })
    // new Myquery(sql, (err, r) => {
    //     let code = 200,
    //         data = r,
    //         msg = '成功';
    //     if (err) {
    //         code = 500;
    //         msg = "失败";
    //         data = null
    //     }
    //     res.json(new Result({
    //         msg,
    //         data,
    //         code
    //     }))
    // })
}

module.exports = router